#include <QtGui>
#include <QtDebug>
#include <QtXml>
#include "qtdiary.h"


QtDiary::QtDiary(QWidget* parent):QMainWindow(parent),mCalendar(0),mEntries(0),mDirty(false)
{
//	readFile();	
	createGui();

	mCalendarWidget->setSelectedDate(QDate::currentDate());
//	calendarClicked(QDate::currentDate());

/*	connect(mSaveButton,SIGNAL(clicked()),this,SLOT(saveClicked()));
	connect(mText,SIGNAL(textChanged()),this,SLOT(textChanged()));
	connect(mEditSubject,SIGNAL(textChanged(const QString&)),this,SLOT(textChanged()));
	connect(mTree,SIGNAL(itemDoubleClicked (QTreeWidgetItem *, int)),this,SLOT(treeDoubleClicked(QTreeWidgetItem *, int)));*/
}

QtDiary::~QtDiary()
{
//	saveFile();
}

void QtDiary::createGui()
{
    //create the menu
    QToolBar *tb = new QToolBar(this);
    tb->setWindowTitle(tr("File Actions"));
    addToolBar(tb);

    QAction *a;

    a = new QAction(QIcon("filenew.png"), tr("&New"), this);
    a->setShortcut(QKeySequence::New);
    connect(a, SIGNAL(triggered()), this, SLOT(fileNew()));
    tb->addAction(a);

    //create the rest of gui
	mEdit=new QWidget(this);
	mLabelDate=new QLabel(tr("Date"),mEdit);
	mEditDate=new QLineEdit(mEdit);
	mEditDate->setReadOnly(true);
	mLabelSubject=new QLabel(tr("Subject"),mEdit);
	mEditSubject=new QLineEdit(mEdit);
	mText=new QTextEdit(mEdit);
	mSaveButton=new QPushButton(tr("Save"),mEdit);
	
	QGridLayout* grid=new QGridLayout(mEdit);
	grid->addWidget(mSaveButton,0,2);
	grid->addWidget(mLabelDate,0,0);
	grid->addWidget(mEditDate,0,1);
	grid->addWidget(mLabelSubject,1,0);
	grid->addWidget(mEditSubject,1,1);
	grid->addWidget(mText,2,0,1,3);
	
	setCentralWidget(mEdit);

	mCalendar = new QDockWidget(tr("calendar"),this);
	mCalendarWidget=new QCalendarWidget(mCalendar);
	mCalendar->setWidget(mCalendarWidget);
    addDockWidget(Qt::LeftDockWidgetArea, mCalendar);

	mEntries = new QDockWidget(tr("entries"),this);
	mTree=new QTreeWidget(mEntries);
	mTree->setColumnCount(2);
    QTreeWidgetItem *year = new QTreeWidgetItem(QStringList()<<"2008");

    QTreeWidgetItem *e1 = new QTreeWidgetItem(year,QStringList()<<"Oct-1"<<"sprint review");
    QTreeWidgetItem *e2 = new QTreeWidgetItem(year,QStringList()<<"Oct-2"<<"celebration");
        year->setExpanded(true);
    mTree->addTopLevelItem(year);

	//populateTree();	

	mEntries->setWidget(mTree);
	addDockWidget(Qt::LeftDockWidgetArea, mEntries);

	connect(mCalendarWidget,SIGNAL(clicked(const QDate&)),this,SLOT(calendarClicked(const QDate&)));
}

/*void QtDiary::populateTree()
{
	mTree->clear();
	qSort(mEntryList);
	QList<QTreeWidgetItem*> list;
	
	int yr=0,mt=0;
	QTreeWidgetItem* prevm=0;
	for(QList<Entry>::iterator i=mEntryList.begin();i!=mEntryList.end();++i)
	{
		if(yr!=(*i).year)
		{
			yr=(*i).year;mt=0;
			QTreeWidgetItem *yearItem=new QTreeWidgetItem((QTreeWidgetItem*)0,QStringList()<<QString("%1").arg(yr));
			list.append(yearItem);
			if(yr==QDate::currentDate().year())
				mTree->expandItem(yearItem);
			//qDebug()<<"created new year:"<<yr<<endl;
		}
		if(mt!=(*i).month)
		{
			mt=(*i).month;
			if(prevm)
				list.back()->addChild(prevm);
			prevm=new QTreeWidgetItem(list.back(),QStringList()<<QDate::shortMonthName(mt));				
			if(mt==QDate::currentDate().month())
				mTree->expandItem(prevm);
			//qDebug()<<"created new mt:"<<mt<<endl;
		}
		
		{
			//qDebug()<<"adding day:"<<QString("%1").arg((*i).day)<<QString("%1").arg((*i).subject);
			//days add all days to cur month
			prevm->addChild(new QTreeWidgetItem(prevm,QStringList()	<<QString("%1").arg((*i).day)
																	<<QString("%1").arg((*i).subject)));
			QDate date(yr,mt,(*i).day);
			markDay(date);//mark the day since it has some entry
		}
		
	}if(prevm)list.back()->addChild(prevm);
	mTree->insertTopLevelItems(0,list);

}

void QtDiary::readFile()
{
	QFile file("darc.xml");
 	if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
         return;

	QXmlStreamReader reader(&file);
	while(!reader.atEnd())
	{
		reader.readNext();
		if(reader.isStartElement())
		{	
			if (reader.name() == "qtdiary" && reader.attributes().value("version") == "1")
			{
				while(!reader.atEnd())
				{
					reader.readNext();
					if(reader.isStartElement())
					{
						if(reader.name()=="entry")
						{
								Entry e;
								e.year=reader.attributes().value("year").toString().toInt();
								e.month=reader.attributes().value("month").toString().toInt();
								e.day=reader.attributes().value("day").toString().toInt();
								e.id=reader.attributes().value("id").toString().toInt();

								for(;!reader.atEnd();reader.readNext())
								{
									if(reader.isEndElement())
										break;									
									if(reader.name()=="subject")
									{
										e.subject=reader.readElementText();
									}
									else if(reader.name()=="text")
									{
										e.text=reader.readElementText();
									}									
								}
								mEntryList.push_back(e);
						}						
					}
				}
			}
			else
				return;
		}
	}
	file.close();
}

void QtDiary::saveFile()
{
	QFile file("darc.xml");
	//file.remove("darc.bak");
	if(!file.copy("darc.bak"))
	{
			QMessageBox::warning(this,"warning","cannot backup file!!!<br> please backup manually");
	}
		

	{
		
		if(!file.open(QIODevice::WriteOnly|QIODevice::Text))//make backup before opening in writeonly
		{
			QMessageBox::critical(this,"cannot save","cannot save ur log, better save manually <br>changes not saved!");
			return;
		}
		QXmlStreamWriter writer(&file);
		writer.setAutoFormatting(true);
		writer.writeStartDocument();
		writer.writeStartElement("qtdiary");
    	writer.writeAttribute("version", "1");
		writer.writeStartElement("entries");
		for(QList<Entry>::iterator i=mEntryList.begin();i!=mEntryList.end();i++)
		{
			writer.writeStartElement("entry");
		    writer.writeAttribute("year",QString("%1").arg((*i).year));
			writer.writeAttribute("month",QString("%1").arg((*i).month));
			writer.writeAttribute("day",QString("%1").arg((*i).day));
			writer.writeAttribute("id",QString("%1").arg((*i).id));
			writer.writeTextElement("subject",(*i).subject);
			writer.writeTextElement("text",(*i).text);
			writer.writeEndElement();
		}
		writer.writeEndElement();
		writer.writeEndElement();
		writer.writeEndDocument();
	}
	file.close();
}

void QtDiary::calendarClicked(const QDate& date)
{
	if(mDirty)
	{
		QMessageBox::warning(this,tr("modified"),tr("modified  changes will be lost, please save to continue"));
		return;
	}
	mEditDate->setText(date.toString());
	mText->clear();
	mEditSubject->clear();
	mDate=date;
	
	//search and set text if it is there
	for(QList<Entry>::iterator i=mEntryList.begin();i!=mEntryList.end();i++)
	{
		QDate d((*i).year,(*i).month,(*i).day);
		if(date==d)
		{
			mEditSubject->setText((*i).subject);
			mText->setText((*i).text);
		}
	
	}mDirty=false;
}

void QtDiary::saveClicked()
{
	if(!mDirty)
		return;
	mDirty=false;
	Entry e;
	e.year=mDate.year();
	e.month=mDate.month();
	e.day=mDate.day();
	e.id=1;	//TODO:multiple comment support
	for(QList<Entry>::iterator i=mEntryList.begin();i!=mEntryList.end();++i)
	{
		QDate d((*i).year,(*i).month,(*i).day);
		if(d==mDate)
		{
			mEntryList.erase(i);
			break;
		}
	}
	
	e.subject=mEditSubject->text();
	e.text=mText->toPlainText();
	mEntryList.append(e);
	populateTree();
}

void QtDiary::textChanged()
{
	if(mDirty)
		return;
	mDirty=true;
	
}

void QtDiary::markDay(QDate& date)
{
	QTextCharFormat mark;
    mark.setForeground(Qt::darkBlue);
	mark.setFontUnderline(true);	
	//mark.setFontOverline(true);
	//mark.setToolTip("tooltip");
    mCalendarWidget->setDateTextFormat(date, mark);
}

void QtDiary::treeDoubleClicked(QTreeWidgetItem *i, int c)
{
	//TODO:toimplement tree handling
}
*/